(function($, owner) {
	owner.ctxPath="";
	owner.backendPath="";
	owner.frontPath="";
		
	owner.addCtx=function (path) {
        if (owner.ctxPath == "") {
        	owner.ctxPath = path;
        }
	};
	owner.addBackendPath=function (path) {
        if (owner.backendPath == "") {
        	owner.backendPath = path;
        }
    };
    owner.addFrontPath=function (path) {
        if (owner.frontPath == "") {
        	owner.frontPath = path;
        }
    };
	//log
    owner.log=function (info) {
        console.log(info);
    };
    //当前窗口
    owner.win=function() {
        if (window) {
            return window;
        }
        return null;
    }();
    //父层窗口
    owner.p_win=function() {
        try {
            if (window.parent) {
                return window.parent;
            }
        } catch(e) {}
        if (window) {
            return window;
        }
        return null;
    }();
    //顶层窗口
    owner.t_win=function() {
        try {
            if (window.top) {
                return window.top;
            }
        } catch(e) {}
        try {
            if (window.parent.parent) {
                return window.parent.parent;
            }
        } catch(e) {}
        try {
            if (window.parent) {
                return window.parent;
            }
        } catch(e) {}
        if (window) {
            return window;
        }
        return null;
    }();
    //layer对象
    owner.layer=function() {
        return owner.win.layer;
    }();
    //ParentLayer父层对象
   /* owner.p_layer=function() {
        return owner.p_win.Sys.layer
    }();
    //TopLayer顶层对象
    owner.t_layer=function() {
        return owner.t_win.Sys.layer
    }();*/
	//提示框
    owner.alert=function (info, iconIndex) {
        owner.layer.msg(info, {
            icon:iconIndex
        });
    };
	//信息框
    owner.info=function (info) {
    	owner.layer.alert(info, 0);
    };
	//成功框
    owner.success=function (info) {
    	owner.layer.alert(info, 1);
    };
	//错误框
    owner.error=function (info) {
    	owner.layer.alert(info, 2);
    };
	//询问框
    owner.confirm=function (tip, ensure) {
        owner.layer.confirm(tip,{
            btn: ['确定', '取消']
        }, function (index) {
            if(ensure){
            	ensure();
            }
            owner.layer.close(index);
        }, function (index) {
            owner.layer.close(index);
        });
    };
	//弹窗打开地址,area为空则默认全屏
    owner.open=function (title, url, area, onSuccess) {
        var _opns = {
                type: 2,
                title: title,
                fix: false, //不固定
                maxmin: true,
                content: url,
                success: function(layero, index){
                	if(onSuccess){
                		var iframeWin = owner.win[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                		onSuccess(layero, index, iframeWin);
                	}
                }
            };
    	var isFull = true;
        if(area){
        	isFull = false;
        	_opns["area"]=area;
        }
        var index = owner.layer.open(_opns);
        if(isFull){
        	owner.layer.full(index);
        }
        return index;
    };
	//顶层弹窗打开地址
    owner.open_t=function (title, url, area, onSuccess) {
        var _opns = {
                type: 2,
                title: title,
                fix: false, //不固定
                maxmin: true,
                content: url,
                success: function(layero, index){
                	if(onSuccess){
                		var iframeWin = owner.t_win[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                		onSuccess(layero, index, iframeWin);
                	}
                }
            };
    	var isFull = true;
        if(area){
        	isFull = false;
        	_opns["area"]=area;
        }
        var index = owner.open(_opns);
        if(isFull){
        	owner.full(index);
        }
        return index;
    };
	//父层弹窗打开地址
    owner.open_p=function (title, url, area, onSuccess) {
        var _opns = {
                type: 2,
                title: title,
                fix: false, //不固定
                maxmin: true,
                content: url,
                success: function(layero, index){
                	if(onSuccess){
                		var iframeWin = owner.p_win[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                		onSuccess(layero, index, iframeWin);
                	}
                }
            };
    	var isFull = true;
        if(area){
        	isFull = false;
        	_opns["area"]=area;
        }
        var index = owner.open(_opns);
        if(isFull){
        	owner.full(index);
        }
        return index;
    };
	//弹窗显示html内容
    owner.openHtml=function (title, info, area) {
    	var _area = area?area:['95%', '90%'];
        var display = "";
        if (typeof info == "string") {
            display = info;
        } else {
            if (info instanceof Array) {
                for (var x in info) {
                    display = display + info[x] + "<br/>";
                }
            } else {
                display = info;
            }
        }
        var index = owner.open({
            title: title,
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: _area, //宽高
            content: '<div style="padding: 20px;">' + display + '</div>'
        });
        return index;
    };
	//关闭弹窗
    owner.close=function (index) {
    	owner.close(index);
    };
    //加载框
    owner.loading=function(message, ignoreMessageIfExists) {
        var topJs;
        try {
            top.loadingFlag = true;
            topJs = top.Sys || parent.parent.Sys || parent.Sys
        } catch(e) {}
        if (typeof loadingFlag == "undefined" && topJs) {
            if (typeof topJs.loading == "function") {
                topJs.loading(message);
                return;
            }
        }
        if (message == undefined || message == "") {
            message = "正在加载，请稍后...";
        }
        if (message == "none") {
            return;
        }
        setTimeout(function() {
            if (!Sys.pageLoadingNum) {
                Sys.pageLoadingNum = 0;
            }
            if (!Sys.pageLoadingStyle) {
                if ($("body").hasClass("loading-topline")) {
                    Sys.pageLoadingStyle = 2;
                } else {
                    Sys.pageLoadingStyle = 1;
                }
            }
            if (Sys.pageLoadingStyle == 1) {
                message += '<em onclick="Sys.closeLoading(0, true)">×</em>';
                if ($("#page-loading").length == 0) {
                    $("body").append('<div id="page-loading" onmouseover="$(this).find(\'em\').show()" onmouseout="$(this).find(\'em\').hide()">' + message + "</div>");
                } else {
                    if (!(ignoreMessageIfExists == true)) {
                        $("#page-loading").html(message);
                    }
                }
            } else {
                if (Sys.pageLoadingStyle == 2) {
                    if ($("#page-loading-top").length == 0) {
                        $("body").append('<div id="page-loading-top" class="page-loading-top"></div>');
                        $("#page-loading-top").animate({
                            width: "65%"
                        },
                        2000,
                        function() {
                            $(this).animate({
                                width: "85%"
                            },
                            8000)
                        })
                    }
                }
            }
            Sys.pageLoadingNum++;
        },
        0)
    };
    //关闭加载框
    owner.closeLoading=function(timeout, forceClose) {
        var topJs;
        try {
            top.loadingFlag = true;
            topJs = top.Sys || parent.parent.Sys || parent.Sys;
        } catch(e) {}
        if (typeof loadingFlag == "undefined" && topJs) {
            if (typeof topJs.closeLoading == "function") {
                topJs.closeLoading(timeout, forceClose);
                return;
            }
        }
        setTimeout(function() {
            if (!Sys.pageLoadingNum) {
                Sys.pageLoadingNum = 0;
            }
            Sys.pageLoadingNum--;
            if (forceClose || Sys.pageLoadingNum <= 0) {
                if (Sys.pageLoadingStyle == 1) {
                    $("#page-loading").remove();
                } else {
                    if (Sys.pageLoadingStyle == 2) {
                        $("#page-loading-top").stop().animate({
                            width: "100%"
                        },
                        200,
                        function() {
                            $(this).fadeOut(300,
                            function() {
                                $(this).remove()
                            })
                        })
                    }
                }
                Sys.pageLoadingNum = 0;
            }
        },
        timeout == undefined ? 0 : timeout)
    };
    // ajax请求
    owner.ajax=function(url, data, callback, dataType, async, message) {
    	owner.loading(message ? "正在提交，请稍后...": message);
        $(".btn").attr("disabled", true);
        if (typeof data == "function") {
            message = async;
            async = dataType;
            dataType = callback;
            callback = data;
            data = undefined
        }
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType: dataType ? "json": dataType,
            async: async ? true: async,
            error: function(data) {
                $(".btn").attr("disabled", false);
                owner.error(data.responseText);
                owner.closeLoading(0, true)
            },
            success: function(data, status, xhr) {
                $(".btn").attr("disabled", false);
                owner.closeLoading();
                if (typeof callback == "function") {
                    callback(data, status, xhr);
                } else {
                	owner.success("操作成功!");
                	owner.log(data);
                }
            }
        })
    };
    // ajaxForm请求
    owner.ajaxForm=function(formId, url , callback, dataType, async, message) {
    	owner.loading(message ? "正在提交，请稍后...": message);
        if (typeof url == "function") {
            message = async;
            async = dataType;
            dataType = callback;
            callback = url;
            url = undefined;
        }
    	var formJqueryObj = $("#"+formId);
        $(".btn").attr("disabled", true);
        formJqueryObj.ajaxSubmit({
            type: "POST",
            xhrFields: {
                withCredentials: true
            },
            url: url?url:formJqueryObj.attr("action"),
            dataType: dataType ? "json": dataType,
            async: async ? true: async,
            error: function(data) {
                $(".btn").attr("disabled", false);
                owner.error(data.responseText);
                owner.closeLoading(0, true)
            },
            success: function(data, status, xhr) {
                $(".btn").attr("disabled", false);
                owner.closeLoading();
                if (typeof callback == "function") {
                    callback(data, status, xhr);
                } else {
                	owner.success("操作成功!");
                	owner.log(data);
                }
            }
        })
    };
    owner.sysTabObj=function() {
        try {
            if (top.SysTabObj) {
                return top.SysTabObj;
            }
            if (parent.parent.SysTabObj) {
                return parent.parent.SysTabObj;
            }
            if (parent.SysTabObj) {
                return parent.SysTabObj;
            }
        } catch(e) {}
        if (window.SysTabObj) {
            return SysTabObj;
        }
        return null;
    }();
    owner.addTabPage=function(title, url, closeable) {
    	owner.sysTabObj.addTab(title, url, closeable);
    };
    owner.getCurrentTabPage=function(currentTabCallback) {
    	return owner.sysTabObj.getCurrentTabIndex();
    };
    owner.closeCurrentTabPage=function(preTabCallback) {
    	owner.sysTabObj.closeTab();
    	currentTabCallback();
    };
    owner.windowOpen=function(url, name, width, height) {
        var top = parseInt((window.screen.height - height) / 2, 10),
        left = parseInt((window.screen.width - width) / 2, 10),
        options = "location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes,width=" + width + ",height=" + height + ",top=" + top + ",left=" + left;
        window.open(url, name, options);
    };
    owner.windowClose=function() {
        setTimeout(function() {
            window.opener = null;
            window.open("", "_self");
            window.close();
        },
        100)
    };
    // inputtree显示
	owner.showInputTree=function (inputId, inputTreeContentId, leftOffset, rightOffset) {
        var onBodyDown = function (event) {
            if (!(event.target.id == "menuBtn" || event.target.id == inputTreeContentId || $(event.target).parents("#" + inputTreeContentId).length > 0)) {
                $("#" + inputTreeContentId).fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
            }
        };

        if(leftOffset == undefined && rightOffset == undefined){
            var inputDiv = $("#" + inputId);
            var inputDivOffset = $("#" + inputId).offset();
            $("#" + inputTreeContentId).css({
                left: inputDivOffset.left-15 + "px",
                top: inputDivOffset.top + inputDiv.outerHeight()-18	 + "px"
            }).slideDown("fast");
        }else{
            $("#" + inputTreeContentId).css({
                left: leftOffset + "px",
                top: rightOffset + "px"
            }).slideDown("fast");
        }

        $("body").bind("mousedown", onBodyDown);
    };
    // 获取
    owner.getLink=function(url){
    	var _link = {
			url:url,
			parms:[],
			go:function(){
				var _p = "";
				for (var i=0;i < this.parms.length;i++) {
					if(i==0){
						_p += "?"+this.parms[i];
					}else{
						_p += "&"+this.parms[i];
					}
				}
		    	window.location.href = url+_p;
			},
			set : function (key, value) {
				if (typeof key == "object") {
					for (var i in key) {
						if (typeof i == "function")
							continue;
						this.parms.push([i]+"="+key[i]);
					}
				} else {
					this.parms.push([key]+"="+((typeof value == "undefined") ? $("#" + key).val() : value));
				}
				return this;
			},
    	}
    	return _link;
    };
    //获取树已选节点
    owner.zTreeCheckedNodes=function (zTreeId) {
        var zTree = $.fn.zTree.getZTreeObj(zTreeId);
        var nodes = zTree.getCheckedNodes();
        var ids = "";
        for (var i = 0, l = nodes.length; i < l; i++) {
            ids += "," + nodes[i].id;
        }
        return ids.substring(1);
    };
    //获取点击事件的源对象
    owner.eventParseObject=function (event) {
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        return $(obj);
    };
    //创建更多按钮-用在表格操作列，当操作按钮过多时可以把一些按钮放到更多里.
    owner.createMoreBtn=function (btns) {
    	var actions = [];
		actions.push('<a href="javascript:" class="btnMore" title="更多操作"><i class="fa fa-chevron-circle-right"></i></a>&nbsp;');
		actions.push('<div class="moreItems">');
		$.each(btns,function(i,o){
			actions.push(o);
		})
		actions.push('</div>');			
	return actions.join('');
    };
    // 通用下载
    owner.download=function (url,parms) {
        var $form = $("<form>");   //定义一个form表单
        $form.attr('style', 'display:none');   //在form表单中添加查询参数
        $form.attr('target', '');
        $form.attr('method', 'post');
        $form.attr('action', url);
        Object.keys(parms).forEach(function(key){
            var ipt = $('<input>');
            ipt.attr('type', 'hidden');
            ipt.attr('name', key);
            ipt.attr('value', parms[key]);
            $form.append(ipt);   //将查询参数控件提交到表单上
       });
        $('body').append($form);  //将表单放置在web中
        $form.submit();
    };
    // sessions超时处理
    owner.sessionTimeoutRegistry=function () {
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            complete: function (XMLHttpRequest, textStatus) {
                //通过XMLHttpRequest取得响应头，sessionstatus，
                var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
                if (sessionstatus == "timeout") {
                    //如果超时就处理 ，指定要跳转的页面
                    window.location = owner.backendPath + "/login";
                }
            }
        });
    };
    // 初始化验证
    owner.initValidator=function(formId,fields){
        $('#' + formId).bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: fields,
            live: 'enabled',
            message: '该字段不能为空'
        });
    };
	//layer采用hisui皮肤
    if(window.layer){
    	window.layer.config({
        	extend: 'hisui/style.css', //加载新皮肤
        	skin: 'layer-ext-hisui' //一旦设定，所有弹层风格都采用此主题。
        });
    }
    owner.sessionTimeoutRegistry();
}(jQuery,window.Sys = {}));
